package org.jash.demo2205.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.demo2205.entity.CartItem
import org.jash.demo2205.mvvm.BaseViewModel
import org.jash.demo2205.utils.SingleLiveData

class CartViewModel:BaseViewModel() {
    val cartLiveData by lazy { SingleLiveData<List<CartItem>>() }
    val deleteLiveData by lazy { SingleLiveData<String>() }
    fun getCart() {
        viewModelScope.launch {
            try {
                val res = service.getCart()
                if (res.code == 200) {
                    cartLiveData.postValue(res.data)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
    fun deleteCart(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.deleteCart(mapOf("ids" to id))
                if (res.code == 200) {
                    deleteLiveData.postValue(res.message)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }
}